//模拟数据库
let data_list = [{
        "id": 1,
        "pname": "Soul",
        "price": 18
    },
    {
        "id": 2,
        "pname": "呀",
        "price": 188
    },
    {
        "id": 3,
        "pname": "人走茶凉",
        "price": 188
    },
    {
        "id": 4,
        "pname": "哈",
        "price": 188
    }
]

//展示数据
let fn_data = async(ctx, next) => {
    ctx.body = data_list;
}

//添加数据
let fn_addorEndit = async(ctx, next) => {
    //不管是新增还是编辑这几个数据都是要获取的
    let id = ctx.request.body.id
    let pname = ctx.request.body.pname;
    let price = ctx.request.body.price;

    //判断save引发的请求到底是新增还是编辑
    if (id == '') {
        //已存在相同名称的不可以添加  
        let temp = data_list.filter(item => {
            return item.pname === pname
        })
        if (temp.length === 0) {
            let id = data_list.length + 1 //使id自增
            let obj = {
                id,
                pname,
                price,
            }
            data_list.push(obj) //把新增数据加入数组
            ctx.body = {
                code: 200,
                data: data_list[data_list.length - 1],
                msg: "添加成功"
            }
        } else {
            ctx.body = {
                code: 404,
                data: null,
                msg: "添加失败"
            }
        }
    } else {
        data_list.forEach(item => {
            if (item.id == id) {
                item['pname'] = pname;
                item['price'] = price;
            }
        })
        ctx.body = data_list
    }

}

//得到修改的数据
let fn_endit = async(ctx, next) => {
    let tempdata = data_list.filter(item => {
        return item.id == ctx.request.params.id
    })
    ctx.body = tempdata
}

//删除数据
let fn_delete = async(ctx, next) => {
    let id = ctx.request.params.id
    data_list = data_list.filter(item => {
        if (item.id != id) {
            return true
        }
    })
    data_list = data_list;
    ctx.body = data_list
}

module.exports = {
    //展示数据
    'get /produce': fn_data,

    //查找
    // 'get /produce/': fn_data , 

    //新增
    'post /produce': fn_addorEndit,

    //修改
    'get /produce/get/:id': fn_endit,
    'put /produce': fn_addorEndit,

    //删除 
    'delete /produce/:id': fn_delete
}